<template>
  <div class="table-box">
    <ProTable
      ref="proTableRef"
      title="作业列表"
      :columns="columns"
      :request-api="jobApi.getPageJobDetail"
      :init-param="initParam"
      :data-callback="dataCallback"
    >
      <template #expand="scope">
        <ProTable
          ref="proTableRef"
          title="触发器列表"
          :columns="jobTriggerColumns"
          :data="scope.row.jobTriggers"
          :tool-button="false"
          :pagination="false"
        >
          <template #triggerOperation="triggerScope">
            <el-tooltip content="启动触发器">
              <el-button size="large" type="primary" :icon="VideoPlay" text @click="startTrigger(triggerScope.row)" />
            </el-tooltip>
            <el-tooltip content="暂停触发器">
              <el-button size="large" type="primary" :icon="VideoPause" text @click="pauseTrigger(triggerScope.row)" />
            </el-tooltip>
            <el-tooltip content="编辑触发器">
              <el-button size="large" type="primary" :icon="Edit" text @click="openEditJobTrigger(scope.row)" />
            </el-tooltip>
            <el-tooltip content="删除触发器">
              <el-button size="large" type="danger" :icon="Delete" text @click="delJobTrigger(scope.row)" />
            </el-tooltip>
          </template>
        </ProTable>
      </template>
      <template #operation="scope">
        <el-tooltip content="执行记录">
          <el-button size="small" type="primary" :icon="Timer" text @click="openJobTriggerRecord(scope.row)"> </el-button>
        </el-tooltip>
        <!-- <el-tooltip content="增加触发器">
          <el-button size="small" type="primary" :icon="CirclePlus" text @click="openAddJobTrigger(scope.row)"> </el-button>
        </el-tooltip> -->
        <el-tooltip content="执行作业">
          <el-button type="primary" :icon="CircleCheck" text @click="runJob(scope.row)" />
        </el-tooltip>
        <el-tooltip content="启动作业">
          <el-button type="primary" :icon="VideoPlay" text @click="startJob(scope.row)" />
        </el-tooltip>
        <el-tooltip content="暂停作业">
          <el-button type="primary" :icon="VideoPause" text @click="pauseJob(scope.row)" />
        </el-tooltip>
        <el-tooltip content="取消作业">
          <el-button type="primary" :icon="CircleClose" text @click="cancelJob(scope.row)" />
        </el-tooltip>
        <!-- <el-tooltip content="编辑作业">
          <el-button size="small" type="primary" :icon="Edit" text @click="openEditJobDetail(scope.row)"> </el-button>
        </el-tooltip> -->
        <el-tooltip content="删除作业">
          <el-button type="danger" :icon="Delete" text @click="delJobDetail(scope.row)"> </el-button>
        </el-tooltip>
      </template>
    </ProTable>
    <JobTriggerRecord ref="jobTriggerRecordRef" />
  </div>
</template>
<script setup lang="tsx" name="SysJob">
import { SysJobDetail, SysJobTrigger } from "@/api-services/models/system";
import { SqlSugarPagedList, UnifyResult } from "@/api-services/unifyResult";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps, ProTableInstance } from "@/components/ProTable/interface";
import { jobCreateTypeDict, jobStatusDict } from "./enum/jobDict";
import jobApi from "@/api-services/apis/system/jobApi";
import { ElMessage, ElMessageBox } from "element-plus";
import { CircleCheck, CircleClose, Delete, VideoPause, VideoPlay, Edit, Timer } from "@element-plus/icons-vue";
const JobTriggerRecord = defineAsyncComponent(() => import("./component/jobTriggerRecord.vue"));
const proTableRef = ref<ProTableInstance>();
const jobTriggerRecordRef = ref<InstanceType<typeof JobTriggerRecord>>();
interface InitParam {
  jobId?: string;
  description?: string;
}
const initParam = reactive<InitParam>({});

const dataCallback = (queryRes: UnifyResult<SqlSugarPagedList<SysJobDetail.JobDetailOutput>>) => {
  const data = queryRes.data;
  return {
    items: data.items,
    totalCount: data.totalCount,
    pageIndex: data.pageIndex,
    pageSize: data.pageSize
  };
};
const columns: ColumnProps<SysJobDetail.JobDetailOutput>[] = [
  { type: "expand", width: 40 },
  {
    prop: "jobDetail.jobId",
    label: "作业编号",
    width: 200,
    search: { el: "input", key: "jobId", props: { placeholder: "作业编号" } }
  },
  { prop: "jobDetail.groupName", label: "组名称", width: 100 },
  { prop: "jobDetail.jobType", label: "类型", width: 200 },
  {
    prop: "jobDetail.description",
    label: "描述",
    width: 200,
    search: { el: "input", key: "description", props: { placeholder: "描述信息" } }
  },
  {
    prop: "jobDetail.concurrent",
    label: "执行方式",
    width: 100,
    render: scope => {
      let concurrent = "串行";
      if (scope.row.jobDetail?.concurrent) {
        concurrent = "并行";
      }
      return concurrent;
    }
  },
  {
    prop: "jobDetail.createType",
    label: "创建类型",
    width: 100,
    render: scope => {
      let createType = scope.row.jobDetail?.createType;
      if (!createType) return;
      let typeDict = jobCreateTypeDict[createType];
      return <el-tag type={typeDict?.type}>{typeDict?.label}</el-tag>;
    }
  },
  { prop: "jobDetail.updatedTime", label: "更新时间", width: 200 },
  { prop: "jobDetail.properties", label: "额外数据", width: 150 },
  { prop: "operation", label: "操作", fixed: "right", width: 300 }
];

const jobTriggerColumns: ColumnProps<SysJobTrigger.SysJobTrigger>[] = [
  { prop: "triggerId", label: "触发器编号", width: 200 },
  { prop: "triggerType", label: "类型", width: 200 },
  { prop: "args", label: "参数", width: 150 },
  { prop: "description", label: "描述", width: 200 },

  {
    prop: "status",
    label: "状态",
    width: 100,
    render: scope => {
      let status = scope.row.status;
      if (!status) return;
      let typeDict = jobStatusDict[status];
      return <el-tag type={typeDict?.type}>{typeDict?.label}</el-tag>;
    }
  },
  { prop: "startTime", label: "起始时间", width: 200 },
  { prop: "endTime", label: "结束时间", width: 200 },
  { prop: "lastRunTime", label: "最近运行时间", width: 200 },
  { prop: "nextRunTime", label: "下一次运行时间", width: 200 },
  { prop: "numberOfRuns", label: "触发次数", width: 150 },
  { prop: "maxNumberOfRuns", label: "最大触发次数", width: 150 },
  { prop: "numberOfErrors", label: "出错次数", width: 150 },
  { prop: "maxNumberOfErrors", label: "最大出错次数", width: 150 },
  { prop: "numRetries", label: "重试次数", width: 150 },
  { prop: "retryTimeout", label: "重试间隔ms", width: 150 },
  { prop: "triggerOperation", label: "操作", fixed: "right", width: 200 }
];
// 暂停所有作业
// const pauseAllJob = async () => {
//   await jobApi.pauseAllJob();
//   ElMessage.success("暂停所有作业");
// };

// 执行某个作业
const runJob = async (row: SysJobDetail.JobDetailOutput) => {
  await jobApi.runJob({ jobId: row.jobDetail?.jobId });
  ElMessage.success("执行作业");
};

// 启动某个作业
const startJob = async (row: SysJobDetail.JobDetailOutput) => {
  await jobApi.startJob({ jobId: row.jobDetail?.jobId });
  ElMessage.success("启动作业");
};

// 暂停某个作业
const pauseJob = async (row: SysJobDetail.JobDetailOutput) => {
  await jobApi.pauseJob({ jobId: row.jobDetail?.jobId });
  ElMessage.success("暂停作业");
};

// 取消某个作业
const cancelJob = async (row: SysJobDetail.JobDetailOutput) => {
  await jobApi.cancelJob({ jobId: row.jobDetail?.jobId });
  ElMessage.success("取消作业");
};
// 删除作业
const delJobDetail = (row: SysJobDetail.JobDetailOutput) => {
  ElMessageBox.confirm(`确定删除作业：【${row.jobDetail?.jobId}】?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    await jobApi.deleteJobDetail({ jobId: row.jobDetail?.jobId });
    handleQuery();
    ElMessage.success("删除成功");
  });
};
// 查询操作
const handleQuery = async () => {
  proTableRef.value?.getTableList();
};
//启动触发器
const startTrigger = async (row: SysJobTrigger.SysJobTrigger) => {
  await jobApi.startTrigger({ jobId: row.jobId, triggerId: row.triggerId });
  ElMessage.success("启动触发器");
};

// 暂停触发器
const pauseTrigger = async (row: SysJobTrigger.SysJobTrigger) => {
  await jobApi.pauseTrigger({ jobId: row.jobId, triggerId: row.triggerId });
  ElMessage.success("暂停触发器");
};

// 打开编辑触发器页面
const openEditJobTrigger = (row: SysJobTrigger.SysJobTrigger) => {
  console.log(row);
};

// 删除触发器
const delJobTrigger = (row: SysJobTrigger.SysJobTrigger) => {
  ElMessageBox.confirm(`确定删除触发器：【${row.triggerId}】?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      await jobApi.deleteJobTrigger({ jobId: row.jobId, triggerId: row.triggerId });
      handleQuery();
      ElMessage.success("删除成功");
    })
    .catch();
};
// // 强制唤醒作业调度器
// const cancelSleep = async () => {
//   await jobApi.cancelSleep();
//   ElMessage.success("强制唤醒作业调度器");
// };

// // 强制触发所有作业持久化
// const persistAll = async () => {
//   await jobApi.persistAll();
//   ElMessage.success("强制触发所有作业持久化");
// };
const openJobTriggerRecord = (row: SysJobDetail.JobDetailOutput) => {
  let param = {
    jobId: row.jobDetail?.jobId
  };
  jobTriggerRecordRef.value?.open(param);
};
</script>
<style lang="scss" scoped>
:deep(.el-scrollbar__bar.is-horizontal) {
  display: block !important;
}
:deep(.el-button) {
  padding: 10px;
}
</style>
